package cn.netuo.bumbersoll.entity;

import android.bluetooth.BluetoothGattCharacteristic;
import android.text.TextUtils;
import android.util.Base64;

import com.google.gson.annotations.SerializedName;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Map;
import java.util.Set;

/**
 * 服务器发出的MQTT消息
 */
public class MqttFromS<T> implements Serializable {
    /**
     * 消息类型
     * ad       : 推送广告
     * act      : 推送命令
     * reboot   : 请求重启
     * resetCmd : 重置相关指令
     * act_auto : 自动执行命令(关机)
     */
    @SerializedName("cmd")
    public String cmd;

    /** 请求ID */
    @SerializedName("requestId")
    public String requestId;

    /** 广告数据 / 命令数据 */
    @SerializedName("data")
    public T data;

    /** 定时执行时间 */
    public long targetTime = -1;

    /** 从map当中获取第一个为未开的action */
    public static MqttFromS<Action> getFirstFromMap(Map<String, MqttFromS<Action>> map){
        if(map == null || map.size() == 0) return null; // 返回null,就意味着关闭蓝牙
        for(Map.Entry<String, MqttFromS<Action>> entrySet : map.entrySet()){
            String              key     = entrySet.getKey();
            MqttFromS<Action>   value   = entrySet.getValue();
//            if(value.data != null && value.data.state == Action.ACTION_SATE_ORGINAL){
                return value;
//            }
        }
        return null;
    }

    /** 从map当中删除指定BluetoothGattCharacteristic的项 */
    public static MqttFromS<Action> removeTargetAction(Map<String, MqttFromS<Action>> map, BluetoothGattCharacteristic characteristic){
        if(map == null || map.size() == 0 || characteristic == null) return null; // 返回null,就意味着关闭蓝牙

        String targetId = "";
        MqttFromS<Action> actionMqttFromS = null;
        for(Map.Entry<String, MqttFromS<Action>> entrySet : map.entrySet()){
            String              key     = entrySet.getKey();
            MqttFromS<Action>   value   = entrySet.getValue();
            Action action = value.data;
            String actionChactUUid = action.cmd.chartId;
            String finishChactUUid = characteristic.getUuid().toString();
            if(!TextUtils.equals(actionChactUUid, finishChactUUid)) continue;
            targetId = value.requestId;
            actionMqttFromS = value;
            break;
        }
        if(TextUtils.isEmpty(targetId)) return null;
        map.remove(targetId);
        return actionMqttFromS;
    }



}
